﻿using BizTalk.ESB.Extensions.SSO.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace BizTalk.ESB.Extensions.SSO.Data
{
    public class SsoConfigDataXml
    {
        public static Sso InitConfigObject(int FieldCount)
        {
            var appflags = new SsoApplicationFlags();
            appflags.AllowLocalAccounts = String.Empty;
            appflags.ConfigStoreApp = String.Empty;
            appflags.EnableApp = String.Empty;

            var app = new Common.SsoApplication();
            app.AppAdminGroup = String.Empty;
            app.AppUserGroup = String.Empty;
            app.Description = String.Empty;
            app.Name = String.Empty;
            app.Flags = appflags;

            app.Field = new SsoApplicationField[FieldCount];
            for (int i = 0; i < FieldCount; i++)
            {
                var field = new SsoApplicationField();
                field.Label = String.Empty;
                field.Masked = String.Empty;
                field.Ordinal = String.Empty;
                field.Value = String.Empty;
                app.Field[i] = field;
            }

            var config = new Sso();
            config.Application = app;

            return config;
        }

        public static XmlDocument SerializeConfig(Sso ApplicationConfiguration)
        {
            var xs = new XmlSerializer(ApplicationConfiguration.GetType());
            var sb = new System.Text.StringBuilder();
            var sw = new System.IO.StringWriter(sb);
            xs.Serialize(sw, ApplicationConfiguration);
            var xdoc = new XmlDocument();
            xdoc.LoadXml(sb.ToString());
            return xdoc;
        }

        public static Sso DeserializeConfig(XmlDocument XmlConfig)
        {
            var AppConfig = new Sso();
            var reader = new XmlNodeReader(XmlConfig.DocumentElement);
            var ser = new XmlSerializer(AppConfig.GetType());
            object obj = ser.Deserialize(reader);
            AppConfig = (Sso)obj;
            return AppConfig;
        }
    }
}
